package com.zxj.geekstudy.mysql.aop;

import com.zxj.geekstudy.mysql.annotation.DynamicDS;
import com.zxj.geekstudy.mysql.datasource.DynamicDataSource;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;

import java.lang.reflect.Method;

@Aspect
public class DynamicDataSourceAop {

    @Pointcut(value = "target(com.zxj.geekstudy.mysql.service.Student2Service)")
    public void pointDsClass() {

    }

    @Pointcut(value = "@annotation(com.zxj.geekstudy.mysql.annotation.DynamicDS)")
    public void pointDs() {

    }

    @Before(value = "pointDsClass() && pointDs()")
    public void before() {
        System.out.println("========>切换数据源开始");
    }

    @AfterReturning(value = "pointDsClass() && pointDs()")
    public void after() {
        System.out.println("========>切换数据源结束");
    }

    @Around(value = "pointDsClass() && pointDs()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        // 切换数据源
        MethodSignature ms = (MethodSignature) joinPoint.getSignature();
        Method m = ms.getMethod();
        DynamicDS dynamicDS = m.getAnnotation(DynamicDS.class);
        DynamicDataSource.setDataSourceType(dynamicDS.value());
        // 执行代理方法
        return joinPoint.proceed();
    }

}
